<template>
  <div>
    <MyTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="(params) => projectApi.riskList({ ...params, projectId: detail.id })"
      :index="true"
      :query-format="queryFormat"
      :auto-load="false"
      list-key="risk_list"
    >
      <template #search>
        <MyTQI>
          <n-input
            v-model:value="queryItems.searchVal"
            type="text"
            placeholder="请输入关键字"
            clearable
          >
            <template #suffix>
              <n-icon size="20" :component="Search"></n-icon>
            </template>
          </n-input>
        </MyTQI>

        <MyTQI>
          <AsyncSelect
            v-model:value="queryItems.riskType"
            placeholder="风险类型"
            dict-value-key="dictId"
            options="RISK_TYPE"
          />
        </MyTQI>
        <MyTQI>
          <AsyncSelect
            v-model:value="queryItems.riskGrade"
            placeholder="风险等级"
            dict-value-key="dictId"
            options="RISK_LEVEL"
            @load-dict="(options) => (levelOptions = options)"
          />
        </MyTQI>
        <MyTQI>
          <AsyncSelect
            v-model:value="queryItems.riskRange"
            placeholder="风险范围"
            :options="rangeOptions"
          />
        </MyTQI>
        <MyTQI :content-width="300">
          <n-date-picker
            v-model:formatted-value="queryItems.timeRange"
            type="daterange"
            clearable
          />
        </MyTQI>
      </template>
      <template #action>
        <n-button v-permission="`risk_add`" type="primary" @click="handleAdd">添加</n-button>
      </template>
    </MyTable>
    <MyDrawer ref="$form" :model-form="model" :disabled="type === 'view'" @submit="handleSubmit">
      <n-form-item label="风险范围" path="riskRange">
        <n-radio-group v-model:value="model.riskRange">
          <n-radio v-for="(item, index) in rangeOptions" :key="index" :value="item.value">
            {{ item.label }}
          </n-radio>
        </n-radio-group>
      </n-form-item>
      <n-form-item
        label="风险类型"
        path="riskType"
        :rule="[{ required: true, message: '请选择风险类型' }]"
      >
        <AsyncSelect v-model:value="model.riskType" dict-value-key="dictId" options="RISK_TYPE" />
      </n-form-item>
      <n-form-item
        label="风险描述"
        path="riskDescribe"
        :rule="[{ required: true, message: '请输入风险描述' }]"
      >
        <n-input
          v-model:value="model.riskDescribe"
          clearable
          :maxlength="600"
          show-count
          type="textarea"
          :autosize="{
            minRows: 5,
          }"
        />
      </n-form-item>
      <n-form-item label="风险等级" path="riskGrade">
        <AsyncSelect v-model:value="model.riskGrade" dict-value-key="dictId" options="RISK_LEVEL" />
      </n-form-item>
      <n-form-item label="解决方案" path="solve">
        <n-input
          v-model:value="model.solve"
          clearable
          :maxlength="600"
          show-count
          type="textarea"
          :autosize="{
            minRows: 5,
          }"
        />
      </n-form-item>
      <n-form-item label="风险解决状态" path="resolutionStatus">
        <AsyncSelect
          v-model:value="model.resolutionStatus"
          :options="statusOptions"
          value-key="dictId"
          label-key="name"
        />
      </n-form-item>
      <n-form-item label="备注" path="notes">
        <n-input
          v-model:value="model.notes"
          clearable
          :maxlength="600"
          show-count
          type="textarea"
          :autosize="{
            minRows: 5,
          }"
        />
      </n-form-item>
    </MyDrawer>
  </div>
</template>
<script setup lang="jsx">
import { getSelArrDicts } from '@/api/dict'
import { Search } from '@vicons/ionicons5'
import { useCrudPro } from '@/hooks/useCrudPro'
import * as projectApi from '@/api/project'
import { onBeforeMount } from 'vue'
defineOptions({ name: 'RiskManage' })
const props = defineProps({
  detail: {
    type: Object,
    default: () => ({}),
  },
})
function queryFormat({ timeRange, ...params }) {
  if (timeRange?.length === 2) {
    const [startTime, endTime] = timeRange
    params.startTime = startTime
    params.endTime = endTime
  }
  return params
}
const queryItems = ref({})
const columns = [
  {
    key: 'name',
    title: '风险范围',
    render: (row) => rangeOptions.value.find((item) => item.value === row.riskRange).label,
  },
  { key: 'riskTypeName', title: '风险类型' },
  { key: 'riskDescribe', title: '风险描述' },
  {
    key: 'riskGrade',
    title: '风险等级',
    render: (row) => (
      <MyStatus type="card" valueKey="dictId" options={levelOptions.value} value={row.riskGrade} />
    ),
  },
  { key: 'solve', title: '解决方案' },
  {
    key: 'resolutionStatus',
    title: '解决状态',
    render: (row) => (
      <MyStatus
        labelKey="name"
        valueKey="dictId"
        options={statusOptions.value}
        value={row.resolutionStatus}
      />
    ),
  },
  { key: 'updateUserName', title: '提交人' },
  { key: 'updateTime', title: '提交时间', render: ({ updateTime }) => $format(updateTime) },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <n-button v-permission="risk_update" text onClick={() => handleEdit(row)}>
            修改
          </n-button>
          <n-button
            v-permission="risk_delete"
            text
            onClick={() =>
              handleDelete(row, {
                title: '删除风险',
                content: `请确定是否删除风险：${row.riskDescribe}`,
              })
            }
          >
            删除
          </n-button>
        </n-flex>
      )
    },
  },
]
const rangeOptions = ref([
  { label: '内部风险', value: 0 },
  { label: '外部风险', value: 1 },
])
const statusOptions = ref([])
async function getStatusOptions() {
  const res = await getSelArrDicts({ codes: 'RISK_RESOLUTION_STATUS' })
  statusOptions.value = res.data.RISK_RESOLUTION_STATUS
}
const levelOptions = ref([])
const { type, model, $form, $table, handleAdd, handleEdit, handleSubmit, handleDelete } =
  useCrudPro({
    name: '风险',
    initForm: {
      id: null,
      riskRange: 0,
      riskType: null,
      riskDescribe: null,
      riskGrade: null,
      solve: null,
      resolutionStatus: null,
      notes: null,
    },
    apis: {
      add: (params) => projectApi.riskAdd({ ...params, projectId: props.detail.id }),
      edit: projectApi.riskEdit,
      del: ({ id }) => projectApi.riskDel(id),
      info: ({ id }) => projectApi.riskInfo(id).then((res) => res.data),
    },
  })
watch(
  () => props.detail.id,
  (val) => {
    if (val) {
      nextTick(() => {
        $table.value.handleQuery()
      })
    }
  },
  {
    immediate: true,
  }
)
onBeforeMount(() => {
  getStatusOptions()
})
</script>
<style lang="scss" scoped></style>
